﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text;
using System.Net;
using System.IO;
using LitJson;
using UnityEngine.Networking;
public class ClientManager : MonoBehaviour
{

    private static ClientManager _instance;

    public delegate void ClientResopnse(string response);
    public delegate void ClientErrorResponse(string response);
    private int TimeLimit = 20;// 秒    
    public static ClientManager Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject Item = new GameObject("ServerManager");
                _instance = Item.AddComponent<ClientManager>();
                DontDestroyOnLoad(Item);
            }
            return _instance;
        }
    }

    //Get请求
    public void GetRequest(string url, string paramData, ClientResopnse response, ClientErrorResponse errorCallback = null,object para1 = null)
    {
        StartCoroutine(AnsyGetRequest(url, paramData, response, errorCallback, para1));
    }

    private IEnumerator AnsyGetRequest(string url, string paramData, ClientResopnse response, ClientErrorResponse errorCallback = null, object para1 = null)
    {
        if (!string.IsNullOrEmpty(paramData))
        {
            url = url + "?" + paramData;
        }
        using (UnityWebRequest www = UnityWebRequest.Get(url))
        {
            string token = PlayerPrefs.GetString(HttpUtils.token);
            if (!String.IsNullOrEmpty(token))
            {
                www.SetRequestHeader("X-token", token);
            }
            www.timeout = TimeLimit;
            yield return www.SendWebRequest();
            if (www.result == UnityWebRequest.Result.ConnectionError)
            {             
                if (errorCallback != null)
                {
                    errorCallback("网络异常");
                }   
            }
            else
            {
                Debug.Log($"code:{www.responseCode}");
                if (www.responseCode == 200)//200表示接受成功
                {
                    response(www.downloadHandler.text);
                    www.Abort();
                }
                else
                {
                    if (www.responseCode == 500)
                    {

                    }
                    else
                    {
                        if (errorCallback != null)
                        {
                            errorCallback(www.responseCode.ToString());
                        }
                    }
                    www.Abort();
                }
            }
        }
    }
    //post请求 json格式
    public void PostJsonRequest(string url, string postData, ClientResopnse response, ClientErrorResponse errorCallback = null)
    {
        StartCoroutine(PostJsonUrl(url, postData, response, errorCallback));
    }

    private IEnumerator PostJsonUrl(string url, string postData, ClientResopnse response, ClientErrorResponse errorCallback = null)
    {
        using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
        {
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
            www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            www.SetRequestHeader("Content-Type", "application/json;charset=utf-8");

            //www.SetRequestHeader("Transfer-Encoding", "chunked");
            //www.SetRequestHeader("Date",DateTime.Now.ToUniversalTime().ToString("r"));
            //string token = PlayerPrefs.GetString(HttpUtils.token);
            //if (!String.IsNullOrEmpty(token))
            //{
            //    www.SetRequestHeader("X-Token", token);
            //}
            www.timeout = TimeLimit;

            yield return www.SendWebRequest();
            if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                if (errorCallback != null)
                {
                    errorCallback("网络异常");
                } 
            }
            else
            {
                // Show results as text  
                if (www.responseCode == 200)
                {
                    response(www.downloadHandler.text);
                    www.Abort();
                }
                else
                {
                    if (www.responseCode == 500)
                    {

                    }
                    else
                    {
                        if (errorCallback != null)
                        {
                            errorCallback(www.responseCode.ToString());
                        }
                    }
                    www.Abort();
                }
            }
        }
    }

    //post 表单
    public void PostFormRequest(string url, Dictionary<string, object> SendInfo, ClientResopnse response, ClientErrorResponse errorCallback = null)
    {
        StartCoroutine(PostFormUrl(url, SendInfo, response, errorCallback));
    }

    private IEnumerator PostFormUrl(string url, Dictionary<string, object> SendInfo, ClientResopnse response, ClientErrorResponse errorCallback = null)
    {
        WWWForm wwwForm = new WWWForm();

        Dictionary<string, string> Headers = new Dictionary<string, string>();
        if (SendInfo.Count > 0)
        {
            foreach (KeyValuePair<string, object> saveItem in SendInfo)
            {
                wwwForm.AddField(saveItem.Key, saveItem.Value.ToString());
            }
        }

        using (UnityWebRequest www = UnityWebRequest.Post(url, wwwForm))
        {
            string token = PlayerPrefs.GetString(HttpUtils.token);
            if (!String.IsNullOrEmpty(token))
            {
                www.SetRequestHeader("X-token", token);
            }
            www.timeout = TimeLimit;
            yield return www.SendWebRequest();
            if (www.result == UnityWebRequest.Result.ConnectionError)
            {
                if (errorCallback != null)
                {
                    errorCallback("网络异常");
                }    
            }
            else
            {
                if (www.responseCode == 200)
                {
                    response(www.downloadHandler.text);
                    www.Abort();
                }
                else
                {
                    if (www.responseCode == 500)
                    {
                    }
                    else
                    {
                        if (errorCallback != null)
                        {
                            errorCallback(www.responseCode.ToString());
                        }
                    }
                    www.Abort();
                }
            }
        }
    }

    public string PostWebRequest(string postUrl, string paramData)
    {
        string ret = string.Empty;
        try
        {
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(paramData); //转化
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";

            webReq.ContentLength = byteArray.Length;
            Stream newStream = webReq.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);//写入参数
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            response = null;
            webReq = null;
            newStream.Close();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return ret;
    }


    public void PutRequest(string url, string sendInfo, ClientResopnse response, ClientErrorResponse errorCallback = null)
    {
        StartCoroutine(AnsyPutRequest(url, sendInfo, response,  errorCallback));
    }

    private IEnumerator AnsyPutRequest(string url, string sendInfo, ClientResopnse response, ClientErrorResponse errorCallback = null)
    {
        using (UnityWebRequest www = new UnityWebRequest(url, "PUT"))
        {
            if (!string.IsNullOrEmpty(sendInfo))
            {
                byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(sendInfo);
                www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
                www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            }

            string token = PlayerPrefs.GetString(HttpUtils.token);
            if (!String.IsNullOrEmpty(token))
            {
                www.SetRequestHeader("X-token", token);
            }

            www.timeout = TimeLimit;
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                if (errorCallback != null)
                {
                    errorCallback("网络异常");
                }
            }
            else
            {
                if (www.responseCode == 200)//200表示接受成功
                {
                    response(www.downloadHandler.text);
                    www.Abort();
                }
                else
                {
                    if (www.responseCode == 500)
                    {

                    }
                    else
                    {
                        if (errorCallback != null)
                        {
                            errorCallback(www.responseCode.ToString());
                        }
                    }
                    www.Abort();
                }
            }
        }
    }


    //public string GetMD5Code(string url, long tm)  //
    //{
    //    string result = "";
    //    for (int i = 0; i < GlobalInfo.Instance.CheckIndex.Length; i++)
    //    {
    //        result += GlobalInfo.Instance.CheckCode.ToCharArray()[GlobalInfo.Instance.CheckIndex[i]];
    //    }

    //    string url_part = HttpUtils.GetPartUrl(url);

    //    string appType = "";

    //    if (GlobalInfo.Instance.CurAppType == GlobalInfo.APPType.PHONE)
    //    {
    //        appType = "app";
    //    }
    //    else
    //    {
    //        appType = "pad";
    //    }

    //    result = result + tm + url_part + appType;

    //    var md5 = System.Security.Cryptography.MD5.Create();

    //    byte[] source = System.Text.Encoding.UTF8.GetBytes(result);

    //    byte[] info = md5.ComputeHash(source);

    //    StringBuilder sb = new StringBuilder();

    //    for (int i = 0; i < info.Length; i++)
    //    {
    //        sb.Append(info[i].ToString("X2"));
    //    }
    //    return sb.ToString().ToLower();
    //}
}
